package io.gitee.zhangbinhub.acp.cloud.oauth.conf

import cn.dev33.satoken.oauth2.config.SaOAuth2ServerConfig
import cn.dev33.satoken.oauth2.consts.GrantType
import cn.dev33.satoken.oauth2.consts.SaOAuth2Consts
import cn.dev33.satoken.oauth2.data.model.loader.SaClientModel
import cn.dev33.satoken.oauth2.strategy.SaOAuth2Strategy
import io.gitee.zhangbinhub.acp.cloud.oauth.authentication.UserPasswordGrantTypeHandler
import io.gitee.zhangbinhub.acp.cloud.oauth.constant.OauthConstant
import org.noear.solon.annotation.Configuration
import org.noear.solon.annotation.Init

@Configuration
class AcpOauthServerAutoConfiguration(
    private val userPasswordGrantTypeHandler: UserPasswordGrantTypeHandler,
    private val saOAuth2ServerConfig: SaOAuth2ServerConfig
) {
    @Init
    fun configOAuth2Server() {
        mutableListOf<SaClientModel>().apply {
            this.add(
                SaClientModel()
                    .setClientId("test")
                    .setClientSecret("test_sc")
                    .setClientTokenTimeout(600) // 单位秒
                    .setAccessTokenTimeout(600) // 单位秒
                    .setRefreshTokenTimeout(86400) // 单位秒
                    .addContractScopes("ALL", "TEST")
                    .addAllowGrantTypes(
                        GrantType.client_credentials,
                        GrantType.refresh_token,
                        OauthConstant.granterUserPassword
                    )
            )
        }.associateBy { it.clientId }.apply {
            saOAuth2ServerConfig.setClients(this)
        }

        SaOAuth2Consts.Api.authorize = "/oauth/authorize"
        SaOAuth2Consts.Api.token = "/oauth/token"
        SaOAuth2Consts.Api.refresh = "/oauth/refresh"
        SaOAuth2Consts.Api.revoke = "/oauth/revoke"
        SaOAuth2Consts.Api.client_token = "/oauth/client_token"
        SaOAuth2Consts.Api.doLogin = "/oauth/doLogin"
        SaOAuth2Consts.Api.doConfirm = "/oauth/doConfirm"
        SaOAuth2Strategy.instance.registerGrantTypeHandler(userPasswordGrantTypeHandler)
    }
}